package com.itheima.controller;

import com.itheima.domain.Order;
import com.itheima.domain.Product;
import com.itheima.domain.User;
import com.itheima.service.OrderService;
import com.itheima.service.ProductService;
import com.itheima.service.UserService;
import com.itheima.utils.ProductUtils;
import com.itheima.utils.UserUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpSession;
import java.io.File;
import java.util.*;
import java.util.stream.Collectors;

@Controller
public class ProductController {
    @Autowired
    private ProductService productService;
    @Autowired
    private OrderService orderService;
    @Autowired
    private UserService userService;
    @Autowired
    private UserUtils userUtils;
    @Autowired
    private ProductUtils productUtils;

    @GetMapping("/showAllProducts")
    public String showAllProducts(
            @RequestParam(required = false) String keyword,
            @RequestParam(defaultValue = "1") int page,
            @RequestParam(defaultValue = "8") int size,
            @RequestParam(defaultValue = "time_desc") String sort,
            @RequestParam(defaultValue = "0") int categoryId,
            Model model) {
        List<Product> allProducts = productService.AllProducts();
        if (allProducts == null) {
            return "homePage";
        }

        // 根据关键字过滤商品（名称或描述包含关键字）
        if (keyword != null) {
            allProducts = allProducts.stream()
                    .filter(product ->
                            product.getTitle().toLowerCase().contains(keyword.toLowerCase()) ||
                                    product.getDescription().toLowerCase().contains(keyword.toLowerCase()))
                    .collect(Collectors.toList());
        }

        if (categoryId != 0) {
            allProducts = allProducts.stream().filter(
                    product -> categoryId == (product.getCategoryId()))
                    .collect(Collectors.toList());
            model.addAttribute("categoryId", categoryId);
        }

        switch (sort) {
            case "time_asc":
                Collections.sort(allProducts, Comparator.comparing(Product::getCreateTime));
                break;
            case "price_asc":
                Collections.sort(allProducts, Comparator.comparing(Product::getPrice));
                break;
            case "price_desc":
                Collections.sort(allProducts, Comparator.comparing(Product::getPrice).reversed());
                break;
            case "time_desc":
            default:
                Collections.sort(allProducts, Comparator.comparing(Product::getCreateTime).reversed());
                break;
        }

        int totalPages = (int) Math.ceil((double) allProducts.size() / size);
        // 确保page在有效范围内
        page = Math.max(1, Math.min(page, totalPages));
        // 计算起始和结束索引
        int startIndex = (page - 1) * size;
        int endIndex = Math.min(startIndex + size, allProducts.size());
        List<Product> products = allProducts.subList(startIndex, endIndex);

        model.addAttribute("products", products);
        model.addAttribute("currentPage", page);
        model.addAttribute("totalPages", totalPages);
        model.addAttribute("pageSize", size);
        model.addAttribute("sort", sort);
        model.addAttribute("keyword", keyword);

        return "showAllProducts";
    }

    @GetMapping("/productUpload")
    public String showProductUploadForm(HttpSession session) {
        User user = (User) session.getAttribute("user");
        if (user == null) {
            session.setAttribute("error", "请先登录账号!");
            return "redirect:/login";
        }
        return "productUpload";
    }

    @PostMapping("/productUpload")
    public String productUpload(@RequestParam("imageFile") MultipartFile file,
                                Product product, HttpSession session, RedirectAttributes redirectAttributes) {
        User user = (User) session.getAttribute("user");
        System.out.println(file);
        if (file.isEmpty()) {
            redirectAttributes.addFlashAttribute("errorUpload", "请选择要上传的商品图片!");
            return "redirect:/userCenter";
        }
        try {
            product.setUserId(user.getUserId());
            String uploadResult = productService.productUpload(product);
            if (uploadResult != null) {
                redirectAttributes.addFlashAttribute("errorUpload", uploadResult);
                return "redirect:/productUpload";
            } else {
                redirectAttributes.addFlashAttribute("successUpload", "发布商品成功!");
            }
            Product findProduct = productService.findProduct(product);
            if (findProduct == null || findProduct.getProductId() == null) {
                redirectAttributes.addFlashAttribute("errorUpload", "商品信息保存失败!");
                return "redirect:/productUpload";
            }

            String uploadDir = "D:/CBSystem/productPictures/" + findProduct.getProductId() + "/";
            File dir = new File(uploadDir);
            if (!dir.exists()) {
                dir.mkdirs();
            }
            // 生成唯一文件名
            String originalFilename = file.getOriginalFilename();
            String fileExtension = originalFilename.substring(originalFilename.lastIndexOf("."));
            String newFilename = UUID.randomUUID().toString() + fileExtension;
            File dest = new File(uploadDir + newFilename);
            file.transferTo(dest);

            productService.updateImage(newFilename, findProduct.getProductId());

        } catch (Exception e) {
            e.printStackTrace();
        }

        return "redirect:/userCenter";
    }

    @GetMapping("/productCenter")
    public String showMyProducts(HttpSession session,
                                 Model model,
                                 @RequestParam(required = false) String searchKeyword,
                                 @RequestParam(defaultValue = "1") int page,
                                 @RequestParam(defaultValue = "time_desc") String sort,
                                 @RequestParam(defaultValue = "onsale") String tab) {
        User user = (User) session.getAttribute("user");
        if (user == null) {
            session.setAttribute("error", "请先登录账号!");
            return "redirect:/login";
        }

        List<Product> productList = Collections.emptyList();
        ;

        //onsale
        if ("onsale".equals(tab)) {
            productList = productService.findProductsByUserId(user.getUserId());
            productList = productList.stream()
                    .filter(product -> product.getStatus() == 1)
                    .collect(Collectors.toList());
        }

        //sold
        if ("sold".equals(tab)) {
            List<Order> orderList = orderService.findValidOrdersBySellerId(user.getUserId());
            //商品id
            List<Integer> productIds = orderList.stream()
                    .map(Order::getProductId)       // 直接映射，返回 Integer
                    .collect(Collectors.toList());
            productList = productIds.stream()
                    .map(productId -> productService.findProductById(productId))
                    .filter(Objects::nonNull) // 过滤掉查询结果可能为 null 的情况
                    .collect(Collectors.toList());
            productList = orderList.stream()
                    .map(order -> {
                        Product product = productService.findProductById(order.getProductId());
                        if (product != null) {
                            product.setOrderId(order.getOrderId()); // 将 orderId 存入 Product 对象
                        }
                        return product;
                    })
                    .filter(Objects::nonNull)
                    .collect(Collectors.toList());
        }

        //purchased
        if ("purchased".equals(tab)) {
            List<Order> orderList = orderService.findValidOrdersByBuyerId(user.getUserId());
            //商品id
            List<Integer> productIds = orderList.stream()
                    .map(Order::getProductId)       // 直接映射，返回 Integer
                    .collect(Collectors.toList());
            productList = productIds.stream()
                    .map(productId -> productService.findProductById(productId))
                    .filter(Objects::nonNull) // 过滤掉查询结果可能为 null 的情况
                    .collect(Collectors.toList());
            productList = orderList.stream()
                    .map(order -> {
                        Product product = productService.findProductById(order.getProductId());
                        if (product != null) {
                            product.setOrderId(order.getOrderId()); // 将 orderId 存入 Product 对象
                        }
                        return product;
                    })
                    .filter(Objects::nonNull)
                    .collect(Collectors.toList());
        }

        if ("removed".equals(tab)) {
            productList = productService.findProductsByUserId(user.getUserId());
            productList = productList.stream()
                    .filter(product -> product.getStatus() == 0)
                    .collect(Collectors.toList());
        }


        //根据关键词过滤商品项
        if (searchKeyword != null && !searchKeyword.trim().isEmpty()) {
            productList = productList.stream()
                    .filter(productItem -> {
                        Product product = productService.findProductById(productItem.getProductId());
                        return product != null &&
                                (product.getTitle().toLowerCase().contains(searchKeyword.toLowerCase()) ||
                                        product.getDescription().toLowerCase().contains(searchKeyword.toLowerCase()));
                    })
                    .collect(Collectors.toList());
        }

        //排序
        // 修改后的排序代码
        if (productList != null) {
            switch (sort) {
                case "time_asc":
                    productList.sort(Comparator.comparing(Product::getUpdateTime));
                    break;
                case "price_asc":
                    productList.sort(Comparator.comparing(Product::getPrice));
                    break;
                case "price_desc":
                    productList.sort(Comparator.comparing(Product::getPrice).reversed());
                    break;
                case "time_desc":
                default:
                    productList.sort(Comparator.comparing(Product::getUpdateTime).reversed());
                    break;
            }
        }

        int pageSize = 3; // 每页固定显示2个订单
        int totalPages = (int) Math.ceil((double) productList.size() / pageSize);

        // 确保页码有效（不超过范围）
        page = Math.max(1, Math.min(page, totalPages));

        // 4. 截取当前页数据
        int startIndex = (page - 1) * pageSize;
        int endIndex = Math.min(startIndex + pageSize, productList.size());
        List<Product> currentProductList = productList.subList(startIndex, endIndex);

        //调用 Service 获取统计数据
        Map<String, Integer> stats = userService.getUserProductStats(user.getUserId());

        // 添加到 model
        model.addAttribute("productOnsaleQuantity", stats.get("onsale"));
        model.addAttribute("productSoldQuantity", stats.get("sold"));
        model.addAttribute("productPurchasedQuantity", stats.get("purchased"));
        model.addAttribute("productRemovedQuantity", stats.get("removed"));

        model.addAttribute("productList", currentProductList);
        model.addAttribute("currentPage", page);
        model.addAttribute("totalPages", totalPages);
        model.addAttribute("searchKeyword", searchKeyword);
        model.addAttribute("sort", sort);
        model.addAttribute("tab", tab);

        return "ownProducts";
    }

    @RequestMapping("/productRemove")
    public String removeProduct(@RequestParam(required = false) Integer productId,
                                HttpSession session,
                                RedirectAttributes redirectAttributes) {
        int result = productService.downProductById(productId);
        if (result > 0) {
            redirectAttributes.addFlashAttribute("productSuccessInfo", "商品已下架！");
        } else {
            redirectAttributes.addFlashAttribute("productErrorInfo", "商品下架失败，请重试！");
        }
        return "redirect:/productCenter?tab=removed";
    }

    @RequestMapping("/productRestore")
    public String restoreProduct(@RequestParam(required = false) Integer productId,
                                 HttpSession session,
                                 RedirectAttributes redirectAttributes) {
        int result = productService.uploadProductF1(productId);
        if (result > 0) {
            redirectAttributes.addFlashAttribute("productSuccessInfo", "商品已重新上架！");
        } else {
            redirectAttributes.addFlashAttribute("productErrorInfo", "商品上架失败，请重试！");
        }
        return "redirect:/productCenter";
    }

    @RequestMapping("/showProductInfo")
    public String showProductInfo(@RequestParam(required = false) Integer productId,
                                  Model model,
                                  RedirectAttributes redirectAttributes) {
        Product product = productService.findProductById(productId);
        if (product == null) {
            redirectAttributes.addFlashAttribute("productErrorInfo", "访问错误，请重试！");
            return "redirect:/productCenter";
        } else {
            model.addAttribute("product", product);
            model.addAttribute("productUtils", productUtils);
            model.addAttribute("userUtils", userUtils);
        }

        return "showProductInformation";
    }

    @RequestMapping("/productDeleteEver")
    public String deleteProductEver(@RequestParam(required = false) Integer productId,
                                    RedirectAttributes redirectAttributes) {
        int result = productService.deleteProductEver(productId);
        if (result > 0) {
            redirectAttributes.addFlashAttribute("productSuccessInfo", "商品已永久删除！！");
        } else {
            redirectAttributes.addFlashAttribute("productErrorInfo", "商品删除失败，请重试！");
        }
        return "redirect:/productCenter?tab=removed";
    }

    @GetMapping("/productUpdate")
    public String showProductUpdateForm(@RequestParam(required = false) Integer productId,
                                        Model model) {
        Product product = productService.findProductById(productId);
        if (product == null) {
            model.addAttribute("productErrorInfo", "未找到此商品，请重试！");
            return "showProductInfo";
        }
        model.addAttribute("product", product);
        return "productUpdate";
    }

    @PostMapping("/productUpdate")
    public String updateProduct(@RequestParam(value = "imageFile", required = false) MultipartFile file,
                                Product product,
                                HttpSession session,
                                RedirectAttributes redirectAttributes) {
        User user = (User) session.getAttribute("user");
        if (user == null) {
            return "redirect:/login";
        }

        // 验证商品所有权
        Product existingProduct = productService.findProductById(product.getProductId());
        if (existingProduct == null || !existingProduct.getUserId().equals(user.getUserId())) {
            redirectAttributes.addFlashAttribute("productErrorInfo", "无权修改此商品");
            return "redirect:/productCenter";
        }

        try {
            // 更新商品基本信息
            product.setUserId(user.getUserId());
            String updateResult = productService.updateProductInfo(product);

            if (updateResult != null) {
                redirectAttributes.addFlashAttribute("productErrorInfo", updateResult);
                return "redirect:/productEdit?productId=" + product.getProductId();
            }

            // 处理图片更新（如果上传了新图片）
            if (file != null && !file.isEmpty()) {
                String uploadDir = "D:/CBSystem/productPictures/" + product.getProductId() + "/";
                File dir = new File(uploadDir);
                if (!dir.exists()) {
                    dir.mkdirs();
                }

                // 删除旧图片
                if (existingProduct.getImageUrl() != null) {
                    File oldFile = new File(uploadDir + existingProduct.getImageUrl());
                    if (oldFile.exists()) {
                        oldFile.delete();
                    }
                }

                // 保存新图片
                String originalFilename = file.getOriginalFilename();
                String fileExtension = originalFilename.substring(originalFilename.lastIndexOf("."));
                String newFilename = UUID.randomUUID().toString() + fileExtension;
                File dest = new File(uploadDir + newFilename);
                file.transferTo(dest);
                // 更新数据库中的图片路径
                productService.updateImage(newFilename, product.getProductId());
            }

            redirectAttributes.addFlashAttribute("productSuccessInfo", "商品信息更新成功！");
        } catch (Exception e) {
            e.printStackTrace();
            redirectAttributes.addFlashAttribute("productErrorInfo", "商品更新失败：" + e.getMessage());
            return "redirect:/productEdit?productId=" + product.getProductId();
        }

        return "redirect:/showProductInfo?productId=" + product.getProductId();
    }

}
